package com.example.homework7;

import android.content.ContentValues;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;

import java.util.List;

public class RoomCoulomb extends Fragment {
    public RoomCoulomb(){
        super(R.layout.basic_operation);
    }

    private TextView contentTextView;
    private String username;
    private int age;
    private EditText NameText;
    private EditText AgeText;

    @Override
    public void onViewCreated(@NonNull View view, @NonNull Bundle saveInstanceState){
        super.onViewCreated(view,saveInstanceState);

        NameText = getView().findViewById(R.id.NameText);
        AgeText = getView().findViewById(R.id.AgeText);

        //增加一条数据
        Button AddButton = getView().findViewById(R.id.AddBotton);
        AddButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                username = NameText.getText().toString();
                age = Integer.parseInt(AgeText.getText().toString());

                MyRoomDataBase db = MyRoomDataBase.getInstance(getContext());
                User user = new User();
                user.username = username;
                user.age = age;
                db.userDao().insert(user);
            }
        });

        //查询age<18
        Button AgeListButton = getView().findViewById(R.id.AgeListBotton);
        AgeListButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyRoomDataBase db = MyRoomDataBase.getInstance(getContext());
                showUsers(db.userDao().searchUsersByAge(18));
            }
        });

        //查询所有数据
        MyRoomDataBase db = MyRoomDataBase.getInstance(getContext());
        showUsers(db.userDao().getAll());
    }

    private void showUsers(List<User> users){
        contentTextView = getView().findViewById(R.id.contentview);
        StringBuilder stringBuilder = new StringBuilder();
        for (User user:users){
            stringBuilder.append("        id: ").append(user.id)
                    .append("      username: ").append(user.username)
                    .append("      age: ").append(user.age)
                    .append("\n");
        }
        contentTextView.setText(stringBuilder.toString());
    }
}
